<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <link rel="stylesheet" href="../res/css/weui.css" />
    <link rel="stylesheet" href="../res/css/weuix.css" />
    <link rel="stylesheet" href="../res/css/mp_common.css" />
    <link rel="stylesheet" href="../res/css/common.css" />
    <script src="../res/js/zepto.min.js"></script>
    <script src="../res/js/zepto.weui.js"></script>
    <script src="../res/js/mp_common.js?v=1"></script>
    <script src="../res/js/common.js"></script>
	<!-- 微信开放标签 -->
	<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <style type="text/css">
        img {
            border: 1px solid #efefef;
            border-radius: 10px;
            width: 75px;
            height: 75px;
            margin-left: 10px;
        }

        table {
            width: 95%;
            height: 5.5rem;
            border-radius: 10px;
            padding-bottom: 10px;
            margin: 10px;
        }

        table td {
            text-align: left;
            padding: 5px;
            border: none;
            font-size: 14px;
        }

        /* #div_list {
            padding-top: 72px;
        } */

        .weui-cells {
            background: #ffffff;
            margin: 0px;
            position: sticky;
            width: 100%;
            top: 0;
            z-index: 99;
        }

        .dt_header {
            font-size: 18px;
            z-index: 999;
        }

        .weui-btn {
            position: unset;
        }

        .weui-btn:after {
            content: none;
        }

        .weui-btn_primary {
            margin-right: 5px;
            color: #ffffff;
            background-color: #1189ff;
            border-radius: 10px;
        }

        .weui-btn_primary:not(.weui-btn_disabled):active {
            color: #ffffff;
            background-color: #1189ff;
        }

        .weui-table td,
        .weui-table th,
        table td,
        table th {
            line-height: 20px;
            padding-bottom: 0;
        }

        .noFind {
            width: 90%;
            margin: 10px 2.5%;
            display: block;
            text-align: center;
            overflow: hidden;
            font-size: 15px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #353535;
            background-color: #F9F8FE;
        }

        .noFind img {
            width: 198px;
            height: 158px;
            border: none;
            border-radius: 0px;
            margin: 15px;
        }
        /* 1.9.3 */
        .img_box{
            position: relative;
            border-radius: 10px;
            margin-left: 10px;
            overflow: hidden;
            width: 77px;
            height: 75px;
        }

        .img_box img{
            display: block;
            margin: 0;
        }
        /* 医保单标签 */
        .img_box.is-medical-insurance::after{
            position: absolute;
            bottom: 0px;
            display: block;
            width: 77px;
            height: 23px;
            content: "医保单";
            color: #fff;
            text-align: center;
            line-height: 25px;
            background-color: #00000055;
        }
        
        .orders-filter{
            display: none;
            padding: 4px;
            font-size: 14px;
        }

        .orders-filter .outer-order{
            margin-right: 10px;
        }

        .outer-order, .inner-order{
            border: 1px solid #333;
            border-radius: 8px;
            flex: 1;
            text-align: center;
            padding: 2px 0;
        }

        .orders-filter .active{
            background-color: #1189ff;
            border-color: #1189ff;
            color: #fff;
        }

        .order-state{
            flex:1; 
            height:30px; 
            line-height:30px;
            margin-bottom: 2px;
        }
        .order-state::after{
            display: block;
            content: ' ';
            height: 2px;
            background-color: #fff;
        }
        .order-state.active::after{
            background-color: #1189ff;
        }
    </style>
</head>

<body style="width:100%; min-height:100vh; height: auto;">
    <div class="weui-cells weui-cells_form">
        <div class="weui-flex dt_header" style="padding: 7px 2px;">
            <div class="weui-flex__item">
                <div class="placeholder">
                    <span class="icon icon-109" id="goToindex">
                    </span><span style="padding-left: 33%;">我的订单</span>
                </div>
            </div>
        </div>

        <div class="orders-filter">
            <div class="outer-order active" onclick="filterOrder('outer')">其他订单</div>
            
            <div class="inner-order" onclick="filterOrder('inner')">院内订单</div>
        </div>

        <div style="display:flex; text-align:center; width:100%; font-size:14px;">
            <div class="order-state active" onclick="add_order()">全部</div>
            <div class="order-state" onclick="all_indent()">待付款</div>
            <div class="order-state" onclick="wl_indent()">待自提</div>
            <div class="order-state" onclick="zq_indent()" id="waitingToSend">待发货</div>
            <div class="order-state" onclick="tf_indent()" id="waitingToGet">待收货</div>
            <div class="order-state" onclick="wc_indent()">已完成</div>
            <div class="order-state" onclick="qr_indent()">已取消</div>
        </div>
    </div>

    <div style="width:100%;" id="div_list">
    </div>
</body>

</html>
<script type="text/javascript">
    var user_id = "";
    var group_no = "";
    var doctor_id = "";
    var openid = "";
    var orgid = "";
    var order_id = '',
        wxcode = '',
        money = 0; //支付相关参数
    var inside = false  //院内订单
    switchStateKey(false)

     // 数组去重
    function unique(arr, attribute) {
        var new_arr = [];
        var json_arr = [];
        for (var i = 0; i < arr.length; i++) {
            if (new_arr.indexOf(arr[i][attribute]) == -1) { //  -1代表没有找到
                new_arr.push(arr[i][attribute]); //如果没有找到就把这个name放到arr里面，以便下次循环时用
                json_arr.push(arr[i]);
            }
        }
        return json_arr.sort(function (a, b) {
            return parseFloat(b.prescription_id) - parseFloat(a.prescription_id)
        });
    }
    $(function () {
        user_id = getQst("user_id").trim(); //用户id 
        openid = getQst("openid").trim(); //用户openid
        group_no = getQst("group_no").trim(); //药店id 
        doctor_id = getQst("doctor_id").trim(); //医生id 
        orgid = getQst("orgid").trim(); //医生id 
        isIndex = getQst("isIndex") //是否来自首页

        // 注释掉下面这条会导致无法支付 非测试环境不要注释
        getCode();
        

        indent_list("");
        // 后退到首页
        $('#goToindex').click(function () {
            if (isIndex == 1) {
                goPage('inquiry_doctor_index.htm');
            } else {
                goPage('inquiry_user_personal.htm')
            }
        })

        // his显示院内外订单切换 隐藏待收货
        if (isHis) {
            $('.orders-filter').css('display','flex')
            $('#waitingToGet').hide()
        }
    });

    // 切换院内外订单
    function filterOrder(type) {
        // 院内订单
        if(type == 'inner'){
            switchStateKey(true)
            inside = true
            $('.outer-order').removeClass('active').next().addClass('active')
            $('#waitingToSend').hide()
            add_order()
        // 其他订单
        }else if(type == 'outer'){
            switchStateKey(false)
            inside = false
            $('.inner-order').removeClass('active')
            $('.outer-order').addClass('active')
            $('#waitingToSend').show()
            add_order()
        }
        // console.log(STcancel, STwaitPay, STwaitSend, STsended, STwaitTake, STfinished)
    }

    // 全部
    function add_order() {
        $('.order-state').eq(0).addClass('active').siblings().removeClass('active')
        indent_list("");
    }

    ///待付款
    function all_indent() {
        $('.order-state').eq(1).addClass('active').siblings().removeClass('active')
        indent_list(STwaitPay);
    }
    ///待自提
    function wl_indent() {
        $('.order-state').eq(2).addClass('active').siblings().removeClass('active')
        indent_list(STwaitTake);
    }
    ///待发货
    function zq_indent() {
        $('.order-state').eq(3).addClass('active').siblings().removeClass('active')
        indent_list(STwaitSend);
    }
    ///待收货
    function tf_indent() {
        $('.order-state').eq(4).addClass('active').siblings().removeClass('active')
        indent_list(STsended);
    }
    //   已完成
    function wc_indent() {
        $('.order-state').eq(5).addClass('active').siblings().removeClass('active')
        indent_list(STfinished);
    }
    //   已取消
    function qr_indent() {
        $('.order-state').eq(6).addClass('active').siblings().removeClass('active')
        indent_list(STcancel);
    }

    //订单列表
    let lastPostState = null    //保存上次请求时用的订单状态
    function indent_list(indent_status, resize = 0) {
        paramJson = {
            "current": 1,
            "size": resize || 30,
            "type": indent_status //订单状态：0:已取消 10:未付款(待付款) 20:待发货 30:已发货(待收货) 35:待自提 40:已收货(已完成)  不传默认为全部
        };
        if (isHis && inside) {
            newAjaxPost("/h5/lianjiang/his/getCflzHisPayMentInfoList", paramJson, getDDData);
            return
        }
        lastPostState = indent_status
        newAjaxPost("/h5/thirdParty/getOrderList", paramJson, getDDData);
    }

    function getDDData(rstData) {
        if(rstData.data.total > rstData.data.size){
            // 如果订单总条数大于请求的尺寸，则重新以订单总条数作为尺寸再请求一遍    
            indent_list(lastPostState, rstData.data.total)
            return
        }
        // console.log(rstData);
        if(isHis && inside){
            var timeKey = "createTime",
                numKey = "id",
                stateKey = "payState",
                orderKey = 'outTradeNo'
        }else{
            var timeKey = "create_time",
                numKey = "indent_no",
                stateKey = "indent_state",
                orderKey = "indent_no"
        }
        if (rstData.code == "1") {
            var div_list = "";
            var img_src;
            // 获取用户信息
            // var userJson = {
            // 	"user_type": 1,
            // 	"user_id":rstData.list[0].user_id,
            // 	"rand": Math.random()
            // };
            img_src = "../res/images/drug_Img.png";
            for (var i = 0; i < rstData.data.total; i++) {

                if(!isHis && rstData.data.list[i].paymentMethod === 2){
                    div_list += `<table onclick="window.open('https://wap.qiyitx.com')">`;
                }else{
                    div_list += '<table onclick="To_detailed(\'' + rstData.data.list[i][numKey] + '\',\'' + rstData.data.list[i][stateKey] + '\')">';
                }
                div_list += '<tr>';
                // 1.9.3
                div_list += '<td rowspan="3"><div class="img_box ' + isMedicalInsurance(rstData.data.list[i].paymentMethod === 2) + '"><img class="head_img" src="' + img_src + '" /></div></td>';
                div_list += '<td >订单号：' + rstData.data.list[i][orderKey] + '</td>';
                //判断支付状态
                // if(rstData.data.list[i].pay_status === "0"){
                // 	div_list += '<td style="color:#05C1A9; text-align:right;">未支付</td>';
                // }else{
                // 	div_list += '<td style="color:#05C1A9; text-align:right;">' + rstData.data.list[i][stateKey] + '</td>';
                // }
                div_list += '</tr>';
                div_list += '<tr>';
                div_list += '<td style="font-size:14px;" colspan="2">时间：' + rstData.data.list[i][timeKey] + '</td>';
                div_list += '</tr>';
                div_list += '<tr>';
                switch (Number(rstData.data.list[i][stateKey])) {
                    case STwaitPay:
                        div_list += '<td style="font-size:14px;color: red;" colspan="2" >待付款</td>';
                        break;
                    case STwaitTake:
                        div_list += '<td style="font-size:14px;color: #03A6FF;" colspan="2">待自提</td>';
                        break;
                    case STcancel:
                        div_list += '<td style="font-size:14px;" colspan="2">已取消</td>';
                        break;
                    case STfinished:
                        div_list += '<td style="font-size:14px;color: #05C081;" colspan="2" >已完成</td>';
                        break;
                    case STwaitSend:
                        div_list += '<td style="font-size:14px;color: #03A6FF;" colspan="2">待发货</td>';
                        break;
                    case STsended:
                        div_list += '<td style="font-size:14px;color: #03A6FF;" colspan="2">待收货</td>';
                        break;
                }

                div_list += '</tr>';
                div_list += '<tr>';
                if (rstData.data.list[i][stateKey] == STwaitPay && rstData.data.list[i].payWay != 'offline' && !inside) {
                    div_list +=
                        `<td></td><td style="text-align:right;" colspan="2"><a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary" onclick="orderInfo('${rstData.data.list[i][numKey]}')">去付款</a></td>`;
                } else if (rstData.data.list[i][stateKey] == STwaitSend || rstData.data.list[i][stateKey] == STwaitTake) {
                    div_list +=
                        '<td></td><td style="text-align:right;" colspan="2"><a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary" onclick="Cancel_indent()">申请退款</a></td>';
                } else if (rstData.data.list[i][stateKey] == STsended) {
                    div_list +=
                        `<td></td><td style="text-align:right;" colspan="2"><a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary" onclick="to_logistics('${rstData.data.list[i][numKey]}')">查看物流</a></td>`;
                } else if (rstData.data.list[i][stateKey] == STfinished) {
                    if (rstData.data.list[i].is_delivery == 1) {
                        div_list +=
                            `<td></td><td style="text-align:right;" colspan="2"><a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary" onclick="to_logistics('${rstData.data.list[i][numKey]}')">查看物流</a></td>`;
                    }
                    else{
                        div_list +=
                        `<td></td><td style="text-align:right;" colspan="2"><div style="height:30px"></div></td>`
                    }
                } else if (rstData.data.list[i][stateKey] == STcancel) {
                    div_list +=
                        `<td></td><td style="text-align:right;" colspan="2"><div style="height:30px"></div></td>`
                } else {
                    div_list +=
                        '<td></td><td style="text-align:right;" colspan="2"><a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary">查看详情</a></td>';
                }
                div_list += '</tr>';
                div_list += '</table>';
            }
            if (rstData.data.total == 0) {
                div_list +=
                    '<div class="weui-cell noFind"><img src="../res/images/img_order@2x.png" alt=""><p>订单列表空空如也~</p></div>'
            }
            $("#div_list").html(div_list);
        } else {
            $("#div_list").html(
                '<div class="weui-cell noFind"><img src="../res/images/img_order@2x.png" alt=""><p>订单列表空空如也~</p></div>'
            );
        }
    }

    //订单详情
    function To_detailed(prescription_id, indent_state) {
        console.log(indent_state)
        var event = window.event || arguments.callee.caller.arguments[0]
        event.stopPropagation();
        if (!(isSpace(user_id))) {
            if (indent_state == STwaitPay) {
                //10:未付款(待付款)
                actToPage('user_dtl5.htm?prescription_id=' + prescription_id + '&user_id=' + user_id + '&inside=' + inside);
                // actToPage('inquiry_go_med.htm?id=1558')
            } else if (indent_state == STwaitTake) {
                //35:待自提
                actToPage('user_dtl3.htm?prescription_id=' + prescription_id + '&user_id=' + user_id + '&inside=' + inside);
            } else if (indent_state == STcancel) {
                //订单状态：0:已取消  
                actToPage('user_dtl2.htm?prescription_id=' + prescription_id + '&user_id=' + user_id + '&inside=' + inside);
            } else if (indent_state == STfinished) {
                //40:已收货(已完成)
                actToPage('user_dtl4.htm?prescription_id=' + prescription_id + '&user_id=' + user_id + '&inside=' + inside);
            } else if (indent_state == STwaitSend || indent_state == STsended) {
                //20:待发货 30:已发货(待收货)
                actToPage('user_dtl2.htm?prescription_id=' + prescription_id + '&user_id=' + user_id +
                    "&showDeliveryInfo=1" + '&inside=' + inside);
            }
        }
    }

    //查看物流
    function to_logistics(prescription_id) {
        var event = window.event || arguments.callee.caller.arguments[0]
        event.stopPropagation();
        actToPage('user_logistics.htm?prescription_id=' + prescription_id + '&user_id=' + user_id);
    }

    //退款提醒
    function Cancel_indent() {
        var event = window.event || arguments.callee.caller.arguments[0]
        event.stopPropagation();
        $.alert("退款请联系客服，客服热线：\r\n020-32640557", function () {
            return;
        });
    }

    //获取订单数据
    function orderInfo(orderId) {
        var event = window.event || arguments.callee.caller.arguments[0]
        event.stopPropagation();
        order_id = orderId
        console.log(order_id);
        let params = {
            "order_num": order_id
        }
        newAjaxPost("/h5/thirdParty/orderDetail", params, (json) => {
            if (json.code == 1) {
                money = json.data.indent_total;
                wxDoPay();
            } else {
                msgInfo(json.msg);
            }
        });
    }

    //付款
    function wxDoPay() {
        if (typeof WeixinJSBridge == "undefined") {
            showJSZ("此场景无法调起支付！");
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady();
        }
    }

    function onBridgeReady() {
        var paramJson = {
            "code": "1",
            "h5openid": wxcode,
            "money": money,
            "orderSn": order_id
        }
        newAjaxPost("/h5/prescriptionOrder/initiatePayment", paramJson,wxDoPayOk);
    }

    function wxDoPayOk(jsonInfo) {
        if (jsonInfo.code == '1') {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    "appId": jsonInfo.data.appId, //公众号名称，由商户传入       
                    "timeStamp": jsonInfo.data.timeStamp, //时间戳，自1970年以来的秒数       
                    "nonceStr": jsonInfo.data.nonceStr, //随机串       
                    "package": jsonInfo.data.packageWx, //"prepay_id=" + 
                    "signType": jsonInfo.data.signType, //微信签名方式:       
                    "paySign": jsonInfo.data.paySign //微信签名   
                },
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                        wxDoPaySaveOk(true);
                    } else
                        showJSZ("用户取消支付");
                }
            );
        } else
            showJSZ(jsonInfo.msg);
    }

    function wxDoPaySave() { //修改订单状态接口--后台调用
        var pJson = {
            "order_num": order_id,
            "type": 1
        };
        newAjaxPost("/h5/thirdParty/saveOrder", pJson, wxDoPaySaveOk);
    }

    function wxDoPaySaveOk(jsonInfo) {
        // if (jsonInfo.code == '1') {
        // $("#div_act_btn1").html("");
        // $("#div_act_btn2").html("");
        showJSZ("支付成功！");
        setTimeout(function () {
            //2020.04.08----------
            if (!isSpace(user_id)) {
                actToPage('user_list.htm?user_id=' + user_id);
            } else {
                actToPage('user_list.htm?openid=' + strOpenId);
            }
        }, 2000);
    }

    // 强制关注公众号，获取openid
    function getCode() {
        // if (getUrlParam("code")) {
        //     return false;
        // }
        var code = getUrlParam('code') // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
        var local = window.location.href;
        var APPID = getAPPID();
        if (code == null || code === '') {
            window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + APPID +
                '&redirect_uri=' + encodeURIComponent(local) +
                '&response_type=code&scope=snsapi_base&state=#wechat_redirect'
        } else {
            getOpenId(code) //把code传给后台获取用户信息
        }
    }
    //把code传给后台,得到openid
    function getOpenId(code) {
        // wxcode = code
        var paramJson = {
            "code": code
        };
        newAjaxPost("/h5/prescriptionOrder/getH5OpenId", paramJson, getOpenIdOK);
        // sessionStorage.setItem("code", code);
    }

    function getOpenIdOK(rstData) {
        if (rstData.code == 1) {
            wxcode = rstData.data
        }
    }
    //获取地址栏的参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }
    // 1.9.3
    // 判断是否医保付费,是则返回类名
    function isMedicalInsurance(bool){
        if(bool) return 'is-medical-insurance'
    }
</script>